package netty;

import com.bjtu.boatmq.common.protocol.PacketSource;
import com.bjtu.boatmq.common.protocol.RequestCode;
import com.bjtu.boatmq.common.protocol.SourceEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient2 {
    public static void main(String[] args) throws InterruptedException {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new SourceEncoder());
                        ch.pipeline().addLast(new NettyClientHandler());
                    }
                });

        ChannelFuture future = bootstrap.connect("127.0.0.1", 10110);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int count = 1;
                while (true) {
                    System.out.println("发送一条消息");
/*                    Message message = new Message();
                    message.setTopic("topic_test");
                    message.setBody(new Date() + ": this is a message! ["+count+"]");*/
                    PacketSource packetSource = new PacketSource();
                    packetSource.setCode(RequestCode.SEND_MESSAGE);
                    future.channel().writeAndFlush(packetSource);
                    System.out.println("future:"+future.channel().read());
                    try {
                        Thread.sleep(500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }).start();
    }
}
